package com.tsd.openweixin.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.common.controller.BaseController;
import com.tsd.core.openweixin.model.WechatMessageResult4AccessToken;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.WebUtils;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import com.tsd.openweixin.entity.OpenWeixinSetting;
import com.tsd.system.entity.SysExtSysUserExt;
import com.tsd.system.entity.SysSettingExt;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserBind3rdExt;
import com.tsd.system.service.SysExtSysUserService;
import com.tsd.system.service.SysSettingService;
import com.tsd.system.vo.OpenSetting;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClasxsName: WeixinController
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2021/7/18 18:39
 * @Version: 1.0
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
public class OpenWeixinController extends BaseController {

    //微信网页授权登录
    public static final String URL_QRCONNECT = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
    //微信公众号授权登录
    public static final String URL_AUTHORIZE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect";
    //通过code获取access_token
    public static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    //检验授权凭证（access_token）是否有效
    public static final String URL_AUTH = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s";
    //刷新或续期access_token使用
    public static final String URL_REFRESH_TOKEN = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";
    //获取用户个人信息（UnionID机制）
    public static final String URL_USERINFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    private static final Integer TOKEN_EXPIRED_SECONDS = null;
    private static String encodingAESKey;
    private static final WebUtils WEB_UTILS;
    @Resource
    private SysSettingService sysSettingService;
    @Resource
    private SysExtSysUserService sysExtSysUserService;

    static {
        WEB_UTILS = WebUtils.getInstance();
    }


    @ApiOperation(value = "获取当前用户信息")
    @ResponseBody
    @RequestMapping(value = "/wxBind.action")
    public HttpResult<Object> wxBind() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            SysUser sysUser = this.getSysUser();
            SysSettingExt query = new SysSettingExt();
            query.setCode(OpenSetting.SETTING_CODE_WX_OPEN);
            SysSettingExt sysSetting = sysSettingService.getSysSettingByCodeOwnerSid(query);
            OpenWeixinSetting openWeixinSetting = JSON.parseObject(sysSetting.getJson(), OpenWeixinSetting.class);
            String code = HlpUtils.getString(map, "code");
            if (!HlpUtils.isEmpty(code)) {
                String url = String.format(URL_ACCESS_TOKEN, openWeixinSetting.getWx_open_appid(), openWeixinSetting.getWx_open_app_secret(), code);
                String json = WEB_UTILS.getFromURL(url);
                WechatMessageResult4AccessToken result = JSON.parseObject(json, WechatMessageResult4AccessToken.class);
                if (result.isSuccess()) {
                    String token = result.getAccess_token();
                    String openId = result.getOpenid();
                    SysUserBind3rdExt bind3rdExt = new SysUserBind3rdExt();
                    bind3rdExt.setUser_sid(sysUser.getSid());
                    List<SysUserBind3rdExt> bindList = new ArrayList<>();
                    bindList.add(bind3rdExt);
                    String infoURL = String.format(URL_USERINFO, token, openId);
                    String userInfoJson = WEB_UTILS.getFromURL(infoURL);
                    SysExtSysUserExt info = JSON.parseObject(userInfoJson, SysExtSysUserExt.class);
//                userInfo.setOriginal_id(openWeixinSetting.get());
                    info.setExt_sys_name(sysSetting.getCode());
                    info.setApp_id(openWeixinSetting.getWx_open_appid());
                    info.setSid(sysUser.getSid());
                    info.setOpen_id(result.getOpenid());
                    info.setBindList(bindList);
                    sysExtSysUserService.saveSysExtSysUser(info, null);
                    hr.setCode(ErrorCode.CODE_SUCCESS);
                } else {
                    hr.setMessage(result.getErrcode() + "," + result.getErrmsg());
                }
            } else {
                hr.setMessage("缺少参数code");
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
